<?php
namespace app\admin\controller;
use app\BaseController;
use app\common\OpenApi;
use ZipArchive;

class Upgrade extends BaseController{
    public function getVersion(){
        $action = $this->request->param('action');
        if(empty($action)){
            return $this->error('错误请求');
        }
        return $this->$action();
    }
    public function download(){
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'phpCode/'.$iden.'/'.$v;
        if(!is_dir($dir)){
            mkdir($dir,0777,true);
        }
        $file = $dir.'/'.$v.'.zip';
        $this->client->post('api/download',['save_to'=>$file,'query'=> ['v'=>$v,'iden'=>$iden]]);
        if(file_exists($file)){
            return  $this->success('下载成功');
        }
        return $this->error('下载失败');
        
    }
    public function decompression(){
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'phpCode/'.$iden.'/'.$v;
        $file = $dir.'/'.$v.'.zip';
        if(!file_exists($file)){
            return $this->error('文件不存在');
        }
        $zip=new ZipArchive;//新建一个ZipArchive的对象 
        if($zip->open($file)===TRUE){ 
            $zip->extractTo($dir); 
            $zip->close();
            unlink($file);
            return  $this->success('解压成功');
        }
        return $this->error('解压失败');
    }
    public function move(){
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'phpCode/'.$iden.'/'.$v;
        $phpdir = $dir.'/php/';
        $manageDir = $dir.'/manage/';
        if(is_dir($phpdir)){
            $res = doMoveDir($phpdir, root_path().'app/'.$iden.'/');
            if($res == false) return $this->error ('移动应用PHP文件失败');
        }
        if(is_dir($manageDir)){
            $res = doMoveDir($manageDir, root_path().'public/'.$iden.'/');
            if($res == false) return $this->error ('移动应用后台文件失败');
        }
    
        return $this->success('移动文件成功');
    }
    public function install(){
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'phpCode/'.$iden.'/'.$v;
        $sqlFile = $dir.'/install.sql';
        
        if(!file_exists($sqlFile)){
            return $this->success('执行成功');
        }
       
        $sql = file_get_contents($sqlFile);
        $sqls = explode(';'."\r", $sql);
        if(empty($sql)) return $this->success ('执行成功');
        Db::startTrans();
        try{
            foreach($sqls as $val){
               $val = trim($val);
               if(!empty($val)){
                  Db::execute($val);
               }
            }
            Db::commit();
            return $this->success ('执行成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    public function upgrade(){
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'phpCode/'.$iden.'/'.$v;
        $sqlFile = $dir.'/update.sql';
        if(!file_exists($sqlFile)){
            return $this->success('执行成功');
        }
       
        $sql = file_get_contents($sqlFile);
        $sqls = explode(';'."\r", $sql);
        if(empty($sql)) return $this->success ('执行成功');
        Db::startTrans();
        try{
            foreach($sqls as $val){
               $val = trim($val);
               if(!empty($val)){
                  Db::execute($val);
               }
            }
            Db::commit();
            return $this->success ('执行成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
        
    }
    public function open(){
        $DataSettingLogic = new DataSettingLogic();
        $setting = $DataSettingLogic->getData('open');
        return $this->success($res);
    }
    public function createFromDraft(){
        $OpenPlatformMiniappCodeHelper = new OpenPlatformMiniappCodeHelper();
//        $res = $OpenPlatformMiniappCodeHelper->getTemplateList();
//        var_dump($res);
        $res = $OpenPlatformMiniappCodeHelper->getDrafts();
        if(empty($res['draft_list'])){
            return $this->error('第三方开放平台草稿箱没有草稿,应该上传小程序故障了');
        }
        $draft_id = $res['draft_list'][count($res['draft_list']) - 1]['draft_id'];
        if(empty($draft_id)){
            return $this->error('第三方开放平台草稿箱没有草稿,应该上传小程序故障了');
        }
        $res = $OpenPlatformMiniappCodeHelper->createFromDraft($draft_id);
        if($res['errcode'] != 0){ //如果失败直接报错
            return $this->error($res['errmsg']);
        }
        $list = $OpenPlatformMiniappCodeHelper->getTemplateList();
        if($list['errcode'] != 0){
            return $this->error($res['errmsg']);
        }
        $myList = $list['template_list'];
        $create = array_column($myList,'create_time');
        array_multisort($create,SORT_DESC,$myList);
        $template_id = $myList[0]['template_id'];
        
        // if(null === $myApp = AppModel::find($myAppId)){
        //     return $this->error('我的应用不正确');
        // }
        $AppVersionModel = new AppVersionModel();
        $AppVersionModel->save([
            'app_id' => $myAppId,
            'template' => $templateId,
            'v' => $v,
            'content' => $desc,
        ]);
        // $myApp->status = 1;
        // $myApp->save();
        return $this->success(['template_id'=>$template_id]);
    }
}
